# APScheduler 封装

from apscheduler.schedulers.asyncio import AsyncIOScheduler
from apscheduler.triggers.cron import CronTrigger
from apscheduler.triggers.interval import IntervalTrigger
from apscheduler.job import Job
from apscheduler import jobstores

scheduler = AsyncIOScheduler(jobstores=jobstores)


def start():
    print("定时任务调度器启动")
    scheduler.start()


def add_interval_job(func, seconds: int, job_id: str, **kwargs) -> Job:
    return scheduler.add_job(func, IntervalTrigger(seconds=seconds), id=job_id, **kwargs)


def add_corn_job(func, cron_expr:str, job_id:str, **kwargs) -> Job:
    trigger = CronTrigger.from_crontab(cron_expr)
    return scheduler.add_job(func, trigger, id=job_id, **kwargs)


def remove_job(job_id: str):
    try:
        scheduler.remove_job(job_id)
    except:
        raise RuntimeError("Scheduler has removed")

def pause_job(job_id: str):
    try:
        scheduler.pause_job(job_id)
    except:
        raise RuntimeError("Scheduler has paused")


def resume_job(job_id: str):
    try:
        scheduler.remove_job(job_id)
    except AttributeError:
        raise RuntimeError("Scheduler resume fail")


def get_jobs():
    try:
        return scheduler.get_jobs()
    except AttributeError:
        raise RuntimeError("Scheduler not initialized!")